﻿using System;
using System.Windows;
using WPFTools.Windows;

namespace WPFTools.Dialogs
{
    public class WaitingBox : DpiAwareWindow
    {



        static WaitingBox()
        {
            DefaultStyleKeyProperty.OverrideMetadata(typeof(WaitingBox), new FrameworkPropertyMetadata(typeof(WaitingBox)));
        }



        public string Text
        {
            get { return (string)GetValue(TextProperty); }
            set { SetValue(TextProperty, value); }
        }

        /// <summary>
        /// 文字显示
        /// </summary>
        public static readonly DependencyProperty TextProperty =
            DependencyProperty.Register("Text", typeof(string), typeof(WaitingBox), new PropertyMetadata(""));

       
        private Action _Callback;

        public WaitingBox(Action callback)
        {
            this.WindowStyle = WindowStyle.None;
            this.AllowsTransparency = true;
            this.WindowStartupLocation = WindowStartupLocation.CenterOwner;
            this._Callback = callback;
            this.Loaded += WaitingBox_Loaded;
        }

        public void ChangeText(string msg)
        {
            this.Dispatcher.Invoke(
                new Action(() =>
                    {
                        Text = msg;
                    }
                ));
        }

        void WaitingBox_Loaded(object sender, RoutedEventArgs e)
        {
            this._Callback.BeginInvoke(this.OnComplate, null);
        }

        private void OnComplate(IAsyncResult ar)
        {
            this.Dispatcher.Invoke(new Action(() =>
            {
                this.Close();
            }));
        }
        /// <summary>
        /// 显示等待框，owner指定宿主视图元素，callback为需要执行的方法体（需要自己做异常处理）。
        /// 目前等等框为模式窗体
        /// </summary>
        public static void Show(FrameworkElement owner, Action callback, string mes = "有一种幸福，叫做等待...")
        {
            WaitingBox win = new WaitingBox(callback);
            Window pwin = Window.GetWindow(owner);
            win.Owner = pwin;
            win.Text = mes;
            var loc = owner.PointToScreen(new Point());
            win.Left = loc.X + (owner.ActualWidth - win.Width) / 2;
            win.Top = loc.Y + (owner.ActualHeight - win.Height) / 2;
            win.ShowDialog();
        }

    }
}
